package com.apache.common;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.apache.api.vo.ResultEntity;
import com.apache.client.FlowCoreClient;
import com.apache.client.UctCoreClient;
import com.apache.client.UctOldCoreClient;
import com.apache.database.model.Page;
import com.apache.tools.PropertiesUtils;
import com.apache.tools.StrUtil;
import com.apache.uct.common.Root;
import com.apache.uct.common.entity.Act;
import com.apache.uct.common.entity.Org;
import com.apache.uct.common.entity.Role;
import com.apache.uct.common.entity.Sys;
import com.apache.uct.common.entity.User;

/**
 * 
 * <p>@Description 工作流客户端工具类
 * <p>@Copyright(c)2013:东吴软件技术有限公司
 * <p>@Author: lvcai
 * <p>@Create Date 2013-7-29 下午06:40:13
 * <p>@Modified By:lvcai
 * <p>@Modified Date:2013-7-29 下午06:40:13
 * <p>@version v1.0
 */
public class FlowClientUtil {
	public static String REMOTE_SERVER = PropertiesUtils.getInstance().getValueByProperty(
			"/config/uct_client.properties", "uct_server");
	private static Logger logger = LoggerFactory.getLogger(FlowClientUtil.class);

	/**
	 * 
	 * @param fatherId
	 * @param sysEname
	 * @return
	 * <p>@description 根据系统标识，fatherId获取该系统下的权限  返回json类型字符串
	 * <p>@version 1.0
	 * <p>@author lvcai
	 * <p>@update 2013-7-29 下午06:41:22
	 */
	public static String getAllActList(String fatherId, String sysEname) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("sysEname", sysEname);
		paramMap.put("fatherId", fatherId);

		try {
			String root = FlowCoreClient.getActTree(paramMap);
			Document document = null;
			if (StrUtil.isNotNull(root)) {
				document = DocumentHelper.parseText(root);
				Element rootElement = null;
				rootElement = document.getRootElement();

				//获取result节点信息，以此判断执行是否成功
				String result = rootElement.elementText("result");

				if ("true".equals(result)) {//成功
					String jsonInfo = rootElement.elementText("jsonInfo");
					if (jsonInfo != null && !"".equals(jsonInfo)) {
						return jsonInfo;
					}
				} else {
					String errMsg = rootElement.elementText("errmsg");
					logger.error("根据系统标识,fatherId获取该系统下的权限数失败，失败原因" + errMsg);
				}
			} else {
				logger.error("warging-----------getAllActList()获取的document对象为空------------------");
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return "";
	}

	/**
	 * <p>@description 查询权限列表
	 * <p>@update 2016-02-02
	 */
	public static List<Act> getActList(Map<String, Object> paramMap) {
		boolean isPageFlag = false;
		for (String key : paramMap.keySet()) {
			if ("pageSize".equals(key) || "pageIndex".equals(key)) {
				isPageFlag = true;
				break;
			}
		}
		List<Act> actList = null;
		Page pageList = null;
		ResultEntity root = UctCoreClient.searchActByReflect(paramMap);
		if ("true".equals(root.getResult())) {
			if (isPageFlag) {
				pageList = (Page) root.getEntity();
				actList = pageList.getPageObjects();
			} else {
				actList = (List<Act>) root.getEntity();
			}
		} else {
			logger.error("权限资源查询失败:" + root.getMessage());
		}

		return actList;
	}

	/**
	 * 
	 * @param sysEname
	 * @return
	 * <p>@description 根据系统标识获取该系统下的角色，如果sysEname为空，则获取所有的角色
	 * <p>@version 1.0
	 * <p>@author lvcai
	 * <p>@update 2013-7-29 下午06:42:15
	 */
	public static List<Role> getAllRoleList(Map<String, String> paramMap) {
		List<Role> roleList = null;
		Root root = UctOldCoreClient.searchRoleByReflect(paramMap);
		if ("true".equals(root.getResult())) {
			Page page_role = (Page) root.getEntity();
			roleList = page_role.getPageObjects();
		} else {
			roleList = new ArrayList<Role>();
			logger.error("根据系统标识获取该系统下的角色，失败原因:" + root.getInfo());
		}
		return roleList;
	}

	/**
	 * 
	 * @param Map<String, String> paramMap
	 * @return
	 * <p>@description 根据参数查询角色列表
	 */
	public static List<Role> getRoleList(Map<String, Object> paramMap) {
		boolean isPageFlag = false;
		for (String key : paramMap.keySet()) {
			if ("pageSize".equals(key) || "pageIndex".equals(key)) {
				isPageFlag = true;
				break;
			}
		}

		List<Role> roleList = null;
		Page pageList = null;
		ResultEntity root = UctCoreClient.searchRoleByReflect(paramMap);
		if ("true".equals(root.getResult())) {
			if (isPageFlag) {
				pageList = (Page) root.getEntity();
				roleList = pageList.getPageObjects();
			} else {
				roleList = (List<Role>) root.getEntity();
			}
		} else {
			logger.error("查询角色失败:" + root.getMessage());
		}
		return roleList;
	}

	public static List<User> getUserList(Map<String, Object> paramMap) {
		boolean isPageFlag = false;
		for (String key : paramMap.keySet()) {
			if ("pageSize".equals(key) || "pageIndex".equals(key)) {
				isPageFlag = true;
				break;
			}
		}

		List<User> userList = null;
		Page pageList = null;

		ResultEntity root = UctCoreClient.searchUserByReflect(paramMap);
		if ("true".equals(root.getResult())) {
			if (isPageFlag) {
				pageList = (Page) root.getEntity();
				userList = pageList.getPageObjects();
			} else {
				userList = (List<User>) root.getEntity();
			}
		} else {
			userList = new ArrayList<User>();
			logger.error("查询所有用户失败:" + root.getMessage());
		}
		return userList;
	}

	/**
	 * 
	 * @param actId
	 * @param crossDept
	 * @param deptId
	 * @return
	 * <p>@description 根据权限id,跨部门类型，部门id获取用户
	 * <p>@version 1.0
	 * <p>@author lvcai
	 * <p>@update 2013-7-29 下午06:43:00
	 */
	public static String getUserStr(String roleId, String crossDept, String deptId) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("roleId", roleId);
		paramMap.put("deptcross", crossDept);
		paramMap.put("deptId", deptId);

		String returnInfo = "";
		try {
			String root = FlowCoreClient.getUsersStr(paramMap);
			String users = null;
			Document document = null;
			if (StrUtil.isNotNull(root)) {
				document = DocumentHelper.parseText(root);
				Element rootElement = null;
				rootElement = document.getRootElement();

				//获取result节点信息，以此判断执行是否成功
				String result = rootElement.elementText("result");

				if ("true".equals(result)) {//成功
					users = rootElement.elementText("users");
				} else {
					String errMsg = rootElement.elementText("errmsg");
					System.out.println("根据权限id,跨部门类型，部门id获取用户，失败原因:" + errMsg);
				}
			} else {
				System.out.println("warging-----------getUserStr()获取的document对象为空------------------");
			}

			if (users != null && !"".equals(users)) {
				returnInfo = users;
			}

		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return returnInfo;
	}

	public static List<Org> getOrgList(Map<String, Object> paramMap) {
		if (null == paramMap) {
			paramMap = new HashMap<String, Object>();
		}
		if (paramMap.size() == 0) {
			paramMap.put("fatherId", "0");
		}

		List<Org> orgList = null;
		ResultEntity root = UctCoreClient.searchOrgByReflect(paramMap);
		if ("true".equals(root.getResult())) {
			orgList = (List<Org>) root.getEntity();
		} else {
			logger.error("查询机构列表失败:" + root.getMessage());
		}

		return orgList;
	}

	public static String getOrgListJson(Map<String, Object> paramMap) {
		if (null == paramMap) {
			paramMap = new HashMap<String, Object>();
		}
		if (paramMap.size() == 0) {
			paramMap.put("fatherId", "0");
		}

		List<Org> orgList = null;
		JSONArray jary = new JSONArray();
		ResultEntity root = UctCoreClient.searchOrgByReflect(paramMap);
		if ("true".equals(root.getResult())) {
			orgList = (List<Org>) root.getEntity();
			int count = orgList.size();
			Org vo = null;
			for (int i = 0; i < count; i++) {
				vo = orgList.get(i);
				JSONObject jvo = new JSONObject();
				jvo.put("id", vo.getOrgId());
				jvo.put("text", vo.getOrgCname());
				if (vo.getSubCount() != null && vo.getSubCount() > 0) {
					jvo.put("state", "closed");
				} else {
					jvo.put("state", "opened");
				}
				jary.add(jvo);
				vo = null;
			}

		} else {
			logger.error("查询机构列表失败:" + root.getMessage());
		}

		return jary.toString();
	}

	/**
	 * description:查询系统列表  
	 * @return  
	 */
	public static List<Sys> getSysList(Map<String, Object> paramMap) {

		boolean isPageFlag = false;
		for (String key : paramMap.keySet()) {
			if ("pageSize".equals(key) || "pageIndex".equals(key)) {
				isPageFlag = true;
				break;
			}
		}
		List<Sys> sysList = null;
		Page pageList = null;
		ResultEntity root = UctCoreClient.searchSysByReflect(paramMap);
		if ("true".equals(root.getResult())) {
			if (isPageFlag) {
				pageList = (Page) root.getEntity();
				sysList = pageList.getPageObjects();
			} else {
				sysList = (List<Sys>) root.getEntity();
			}
		} else {
			logger.error("权限资源查询失败:" + root.getMessage());
		}

		return sysList;
	}

}
